package de.unikoblenz.west.csxpoi.server.connector;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;

import de.unikoblenz.west.csxpoi.server.*;

/**
 * Connector to a datastore that communicates via GET/POST-Requests
 * 
 * @author Yassin Nachite
 * 
 */
abstract class HttpConnector extends SourceConnector {

	public HttpConnector() {
		this.repositoryID = "sparql/";
		initialize();
	}

	public HttpConnector(String serverAdress, String repositoryID) {
		this.repositoryID = "sparql/";
		if (serverAdress != "") {
			this.serverAdress = serverAdress;
			this.repositoryID = repositoryID;
		}
		initialize();
	}

	@Override
	public void initialize() {
		try {
			url = new URL(serverAdress + repositoryID);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Sends a query to the datastore
	 * 
	 * @param query
	 * @return formatted result of the query
	 */
	public List<String> sendRequest(String query) {
		try {
			try {

				StringBuffer buffer = new StringBuffer();
				conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("POST");

				conn.setDoOutput(true);
				OutputStreamWriter wr = new OutputStreamWriter(
						conn.getOutputStream());
				wr.write(query);
				wr.flush();

				BufferedReader rd = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
				String line;
				while ((line = rd.readLine()) != null) {
					buffer.append(line);
				}
				wr.close();
				rd.close();
				return formatResult(buffer.toString());

			}

			catch (IOException e) {
				e.printStackTrace();
				throw new ServerException();
			} catch (Exception e) {
				e.printStackTrace();
				throw new ServerException();
			}
		} catch (ServerException e) {
			e.printStackTrace();
		} finally {
			conn.disconnect();
		}
		return null;
	}

}
